<template>
  <div class="category-detail-page">
    <HeaderNav />
    
    <div class="main-container">
      <!-- 侧边分类导航 -->
      <div class="sidebar">
        <div class="sidebar-title">
          <div class="sidebar-title-icon">分</div>
          全部分类
        </div>

        <ul class="category-menu">
          <li
            v-for="category in categoryList"
            :key="category.id"
            class="category-item"
            :class="{ active: category.id === currentCategoryId }"
            @click="handleCategoryClick(category.id)"
          >
            <span class="category-icon">{{ getCategoryIcon(category.categoryName) }}</span>
            {{ category.categoryName }}
          </li>
        </ul>
      </div>

      <!-- 内容区域 -->
      <div class="content">
        <!-- 面包屑导航 -->
        <div class="breadcrumb">
          <span class="breadcrumb-item" @click="$router.push('/home')">首页</span>
          <span class="breadcrumb-separator">/</span>
          <span class="breadcrumb-item" @click="$router.push('/products')">商品分类</span>
          <span class="breadcrumb-separator" v-if="categoryInfo">/</span>
          <span class="breadcrumb-item active" v-if="categoryInfo">{{ categoryInfo.categoryName }}</span>
        </div>

        <!-- 筛选区域 -->
        <div class="filter-section">
          <div class="filter-header">
            <div class="filter-title">筛选条件</div>
            <div class="filter-actions">
              <button
                class="filter-btn"
                :class="{ active: filterType === 'all' }"
                @click="filterType = 'all'; handleFilterChange()"
              >
                全部
              </button>
              <button
                class="filter-btn"
                :class="{ active: filterType === 'new' }"
                @click="filterType = 'new'; handleFilterChange()"
              >
                新品
              </button>
              <button
                class="filter-btn"
                :class="{ active: filterType === 'hot' }"
                @click="filterType = 'hot'; handleFilterChange()"
              >
                热销
              </button>
            </div>
          </div>

          <div class="filter-content">
            <div class="filter-group">
              <div class="filter-label">价格:</div>
              <div class="filter-options">
                <div
                  class="filter-option"
                  :class="{ active: priceRange === 'all' }"
                  @click="priceRange = 'all'; handleFilterChange()"
                >
                  全部
                </div>
                <div
                  class="filter-option"
                  :class="{ active: priceRange === '0-50' }"
                  @click="priceRange = '0-50'; handleFilterChange()"
                >
                  0-50元
                </div>
                <div
                  class="filter-option"
                  :class="{ active: priceRange === '50-100' }"
                  @click="priceRange = '50-100'; handleFilterChange()"
                >
                  50-100元
                </div>
                <div
                  class="filter-option"
                  :class="{ active: priceRange === '100+' }"
                  @click="priceRange = '100+'; handleFilterChange()"
                >
                  100元以上
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 排序区域 -->
        <div class="sort-section">
          <div class="sort-options">
            <div
              class="sort-option"
              :class="{ active: sortBy === 'default' }"
              @click="handleSortChange('default')"
            >
              综合
            </div>
            <div
              class="sort-option"
              :class="{ active: sortBy === 'sales' }"
              @click="handleSortChange('sales')"
            >
              销量
            </div>
            <div
              class="sort-option"
              :class="{ active: sortBy === 'price' }"
              @click="handleSortChange('price')"
            >
              价格
            </div>
            <div
              class="sort-option"
              :class="{ active: sortBy === 'time' }"
              @click="handleSortChange('time')"
            >
              新品
            </div>
          </div>

          <div class="product-count">
            共找到 {{ total }} 件商品
          </div>
        </div>

        <!-- 商品列表 -->
        <div class="product-grid" v-loading="loading && pagination.current === 1">
          <ProductCard
            v-for="product in productList"
            :key="product.id"
            :product="product"
          />
        </div>

        <!-- 空状态 -->
        <el-empty
          v-if="!loading && productList.length === 0"
          description="该分类下暂无商品"
        />

        <!-- 加载更多提示 -->
        <div class="load-more" v-if="total > productList.length">
          <el-button 
            v-if="!loadingMore" 
            type="primary" 
            plain 
            @click="loadMore"
            style="width: 100%"
          >
            加载更多
          </el-button>
          <div v-else class="loading-more-text">
            <el-icon class="is-loading"><Loading /></el-icon>
            加载中...
          </div>
        </div>

        <!-- 没有更多数据提示 -->
        <div class="no-more" v-if="total > 0 && productList.length >= total && productList.length > 0">
          已加载全部 {{ total }} 件商品
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import HeaderNav from '@/components/HeaderNav.vue'
import ProductCard from '@/components/ProductCard.vue'
import { getCategoryDetail, getCategoryList } from '@/api/category'
import { getProductList } from '@/api/product'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const loadingMore = ref(false)
const categoryList = ref([])
const categoryInfo = ref(null)
const currentCategoryId = ref(null)
const productList = ref([])
const total = ref(0)
const hasMore = ref(true)

const filterType = ref('all') // all, new, hot
const priceRange = ref('all') // all, 0-50, 50-100, 100+
const sortBy = ref('default') // default, sales, price, time
const priceOrder = ref('') // asc, desc

const pagination = reactive({
  current: 1,
  size: 24
})

// 获取分类图标
const getCategoryIcon = (categoryName) => {
  const iconMap = {
    '食品生鲜': '🍎',
    '家居日用': '🏠',
    '粮油调味': '🛒',
    '休闲零食': '🍵',
    '节日礼品': '🎁',
    '个人护理': '🧴',
    '服装鞋帽': '👕',
    '数码家电': '📱'
  }
  return iconMap[categoryName] || '📦'
}

// 加载分类列表
const loadCategories = async () => {
  try {
    const res = await getCategoryList()
    if (res.code === 200 && res.data) {
      categoryList.value = res.data
    }
  } catch (error) {
    console.error('加载分类列表失败:', error)
  }
}

// 加载分类信息
const loadCategoryInfo = async (categoryId) => {
  try {
    const res = await getCategoryDetail(categoryId)
    if (res.code === 200) {
      categoryInfo.value = res.data
    }
  } catch (error) {
    console.error('加载分类信息失败:', error)
  }
}

// 加载商品列表
const loadProducts = async (append = false) => {
  // 如果没有分类ID，不加载
  if (!currentCategoryId.value) {
    return
  }

  if (append) {
    loadingMore.value = true
  } else {
    loading.value = true
    productList.value = []
    pagination.current = 1
  }

  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      categoryId: currentCategoryId.value,
      status: 1 // 只显示上架商品
    }

    // 筛选条件
    if (filterType.value === 'new') {
      // 新品：按创建时间倒序，取前30天内的商品
      params.orderBy = 'create_time'
      params.orderType = 'desc'
    } else if (filterType.value === 'hot') {
      // 热销：按销量倒序
      params.orderBy = 'sales_count'
      params.orderType = 'desc'
    } else {
      // 根据排序方式
      if (sortBy.value === 'sales') {
        params.orderBy = 'sales_count'
        params.orderType = 'desc'
      } else if (sortBy.value === 'price') {
        params.orderBy = 'price'
        params.orderType = priceOrder.value || 'asc'
      } else if (sortBy.value === 'time') {
        params.orderBy = 'create_time'
        params.orderType = 'desc'
      }
    }

    const res = await getProductList(params)
    if (res.code === 200 && res.data) {
      let products = res.data.records || []
      
      // 前端价格筛选
      if (priceRange.value !== 'all') {
        products = products.filter(product => {
          const price = product.price || 0
          if (priceRange.value === '0-50') {
            return price >= 0 && price <= 50
          } else if (priceRange.value === '50-100') {
            return price > 50 && price <= 100
          } else if (priceRange.value === '100+') {
            return price > 100
          }
          return true
        })
      }

      if (append) {
        // 追加数据
        productList.value = [...productList.value, ...products]
      } else {
        // 替换数据
        productList.value = products
      }
      
      total.value = res.data.total || 0
      hasMore.value = productList.value.length < total.value
    } else {
      ElMessage.error(res.message || '加载商品列表失败')
    }
  } catch (error) {
    console.error('加载商品列表失败:', error)
    ElMessage.error('加载商品列表失败: ' + (error.message || '网络错误'))
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loadingMore.value) {
    pagination.current++
    loadProducts(true)
  }
}

// 滚动加载
const handleScroll = () => {
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop
  const windowHeight = window.innerHeight
  const documentHeight = document.documentElement.scrollHeight
  
  // 距离底部200px时加载
  if (scrollTop + windowHeight >= documentHeight - 200) {
    if (hasMore.value && !loadingMore.value && !loading.value) {
      loadMore()
    }
  }
}

// 分类点击
const handleCategoryClick = (categoryId) => {
  if (categoryId === currentCategoryId.value) return
  router.push(`/category/${categoryId}`)
}

// 筛选变化
const handleFilterChange = () => {
  productList.value = []
  pagination.current = 1
  loadProducts()
}

// 排序变化
const handleSortChange = (sort) => {
  if (sort === sortBy.value && sort === 'price') {
    // 价格排序切换升序/降序
    priceOrder.value = priceOrder.value === 'asc' ? 'desc' : 'asc'
  } else {
    sortBy.value = sort
    priceOrder.value = ''
    if (sort === 'price') {
      priceOrder.value = 'asc'
    }
  }
  productList.value = []
  pagination.current = 1
  loadProducts()
}

// 初始化
onMounted(() => {
  const categoryId = Number(route.params.id)
  if (categoryId) {
    currentCategoryId.value = categoryId
    loadCategories()
    loadCategoryInfo(categoryId)
    loadProducts()
    
    // 添加滚动监听
    window.addEventListener('scroll', handleScroll)
  }
})

// 监听路由变化
watch(() => route.params.id, (newId) => {
  if (newId) {
    currentCategoryId.value = Number(newId)
    productList.value = []
    pagination.current = 1
    loadCategoryInfo(currentCategoryId.value)
    loadProducts()
  }
})

// 组件卸载时移除滚动监听
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<style lang="scss" scoped>
.category-detail-page {
  min-height: 100vh;
  background-color: #f5f7fa;

  .main-container {
    max-width: 1200px;
    margin: 20px auto;
    padding: 0 20px;
    display: flex;
    gap: 20px;
  }

  /* 侧边分类导航 */
  .sidebar {
    width: 220px;
    background-color: white;
    border-radius: 12px;
    padding: 20px 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    align-self: flex-start;
    flex-shrink: 0;
  }

  .sidebar-title {
    padding: 0 20px 15px;
    font-weight: 600;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 10px;
    display: flex;
    align-items: center;

    .sidebar-title-icon {
      width: 20px;
      height: 20px;
      background-color: #409EFF;
      border-radius: 4px;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 8px;
      color: white;
      font-size: 12px;
    }
  }

  .category-menu {
    list-style: none;
    padding: 0;
    margin: 0;
  }

  .category-item {
    padding: 12px 20px;
    cursor: pointer;
    transition: all 0.3s;
    display: flex;
    align-items: center;

    &:hover {
      background-color: #f5f7fa;
      color: #409EFF;
    }

    &.active {
      background-color: #f0f9ff;
      color: #409EFF;
      border-right: 3px solid #409EFF;
    }

    .category-icon {
      margin-right: 10px;
      font-size: 16px;
    }
  }

  /* 内容区域 */
  .content {
    flex: 1;
    min-width: 0;
  }

  /* 面包屑导航 */
  .breadcrumb {
    background-color: white;
    border-radius: 12px;
    padding: 15px 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;
    font-size: 14px;

    .breadcrumb-item {
      color: #606266;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #409EFF;
      }

      &.active {
        color: #409EFF;
        cursor: default;
      }
    }

    .breadcrumb-separator {
      margin: 0 8px;
      color: #c0c4cc;
    }
  }

  /* 筛选区域 */
  .filter-section {
    background-color: white;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  }

  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
  }

  .filter-title {
    font-weight: 600;
  }

  .filter-actions {
    display: flex;
    gap: 10px;
  }

  .filter-btn {
    background-color: white;
    border: 1px solid #dcdfe6;
    padding: 6px 12px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s;

    &.active {
      background-color: #409EFF;
      color: white;
      border-color: #409EFF;
    }

    &:hover:not(.active) {
      border-color: #409EFF;
      color: #409EFF;
    }
  }

  .filter-content {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
  }

  .filter-group {
    display: flex;
    align-items: center;
  }

  .filter-label {
    margin-right: 8px;
    font-size: 14px;
    color: #606266;
  }

  .filter-options {
    display: flex;
    gap: 10px;
  }

  .filter-option {
    padding: 6px 12px;
    background-color: #f5f7fa;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s;

    &.active {
      background-color: #409EFF;
      color: white;
    }

    &:hover:not(.active) {
      background-color: #ecf5ff;
      color: #409EFF;
    }
  }

  /* 排序区域 */
  .sort-section {
    background-color: white;
    border-radius: 12px;
    padding: 15px 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .sort-options {
    display: flex;
    gap: 15px;
  }

  .sort-option {
    padding: 6px 12px;
    background-color: #f5f7fa;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s;

    &.active {
      background-color: #409EFF;
      color: white;
    }

    &:hover:not(.active) {
      background-color: #ecf5ff;
      color: #409EFF;
    }
  }

  .product-count {
    color: #909399;
    font-size: 14px;
  }

  /* 商品列表 */
  .product-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    margin-bottom: 30px;

    @media (max-width: 1024px) {
      grid-template-columns: repeat(3, 1fr);
    }

    @media (max-width: 768px) {
      grid-template-columns: repeat(2, 1fr);
    }

    @media (max-width: 480px) {
      grid-template-columns: 1fr;
    }
  }

  /* 加载更多 */
  .load-more {
    text-align: center;
    padding: 30px 0;
  }

  .loading-more-text {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    color: #909399;
    font-size: 14px;
  }

  .no-more {
    text-align: center;
    padding: 30px 0;
    color: #909399;
    font-size: 14px;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .category-detail-page .main-container {
    flex-direction: column;
  }

  .category-detail-page .sidebar {
    width: 100%;
  }

  .category-detail-page .filter-content {
    flex-direction: column;
    align-items: flex-start;
  }

  .category-detail-page .filter-group {
    margin-bottom: 10px;
  }

  .category-detail-page .sort-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
}
</style>
